package rs.mbs2.epics.server.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import rs.mbs2.epics.server.entity.Album;
import rs.mbs2.epics.server.entity.Photo;
import rs.mbs2.epics.server.entity.User;
import rs.mbs2.epics.server.servlet.util.FileManager;
import rs.mbs2.epics.server.session.dao.localinterface.AlbumDaoLocal;
import rs.mbs2.epics.server.session.dao.localinterface.PhotoDaoLocal;

@SuppressWarnings("serial")
public class DeleteAlbumController extends HttpServlet {

	private static Logger log = Logger.getLogger(DeleteAlbumController.class);

	@EJB
	private AlbumDaoLocal albumDao;

	@EJB
	private PhotoDaoLocal photoDao;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String albumId = request.getParameter("id");
		Integer id = Integer.parseInt(albumId);

		Album album = albumDao.findById(id);
		

		//brisanje slika iz albuma
		List<Photo> albumPhotos = photoDao.findPhotosByAlbumId(id);
		
		for (Photo p : albumPhotos) {
			List<Album> albumTemp = albumDao.findAlbumsByPhotoId(p.getId());
			for(Album a : albumTemp) {
				if(!album.equals(a)){
					a.getPhotos().remove(p);
					albumDao.merge(a);
				}
			}
		}


		
		String folderFilesOnServerName = UploadImageController.folderFilesOnServerName;
		String thumbnailsFolderOnServerName = UploadImageController.thumbnailsFolderOnServerName;
		
		User user = (User) request.getSession().getAttribute("user");
		
		String folderPath = getServletContext().getRealPath("")
				+ "\\" + folderFilesOnServerName + "\\" +  user.getId() + "\\" + album.getId() + "\\";
		String folderThumbnailPath = getServletContext().getRealPath("")
				+ "\\" + folderFilesOnServerName + "\\" +  user.getId() + "\\" + album.getId() + "\\" + thumbnailsFolderOnServerName;
		
//		System.out.println("folder path : " + folderPath);
//		System.out.println("folder path thumbnail: " + folderThumbnailPath);

		File folder = new File(folderPath);
		FileManager.delete(folder);
		File folderThumbnails = new File(folderThumbnailPath);
		FileManager.delete(folderThumbnails);
	

		log.info(new Date() + " : obrisan album:" + album.getId());
		albumDao.remove(album);
		
		getServletContext().getRequestDispatcher("/HomeController").forward(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
